import 'package:auntserver/application.dart';
import 'package:auntserver/model/entitys.dart';
import 'package:auntserver/net_api/aunt_datas.dart';
import 'package:auntserver/router_handler/routers.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../app_constants.dart';

class OrderListPage extends StatefulWidget {
  @override
  _OrderListPageState createState() => _OrderListPageState();
}

class _OrderListPageState extends State<OrderListPage>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
  }

  //https://github.com/yongfengnice/flutter_scroll_page_view/blob/main/lib/main.dart

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('订单列表'),
        centerTitle: true,
        automaticallyImplyLeading: false,
        bottom: PreferredSize(
          preferredSize: Size.fromHeight(ScreenUtil().getHeight(44)),
          child: Material(
            color: AuntColors.AWHITE,
            child: TabBar(
              controller: _tabController,
              indicatorColor: AuntColors.AORANGE,
              tabs: [
                Tab(text: '进行中'),
                Tab(text: '完成'),
              ],
            ),
          ),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          OrderListTab("0"),
          OrderListTab("1"),
        ],
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

//unpaidBalance
class OrderListTab extends StatefulWidget {
  final String _complete;

  OrderListTab(this._complete);

  @override
  _OrderListTabState createState() => _OrderListTabState();
}

class _OrderListTabState extends State<OrderListTab>
    with AutomaticKeepAliveClientMixin {
  AuntEntityUserinfo _auntUserinfo;
  int _page = 1;
  bool _haveMore = true;
  RefreshController _refreshController =
      RefreshController(initialRefresh: true);
  List<OrderEntityOrderList> _orderList = [];

  void _onRefresh() async {
    await AuntData.requestOrderList(
      _auntUserinfo.userid.toString(),
      _auntUserinfo.accesstoken,
      widget._complete,
      IdentityStatus.aunt.index.toString(),
    ).then((value) {
      if (value is OrderEntity) {
        _refreshController.refreshCompleted();
        if (value.havemore == 0) {
          _refreshController.loadNoData();
          _haveMore = false;
        }
        _orderList.clear();
        _orderList.addAll(value.orderList);
      } else {
        _refreshController.refreshFailed();
      }
    });
    setState(() {});
  }

  void _onLoading() async {
    _page++;
    await AuntData.requestOrderList(
            _auntUserinfo.userid.toString(),
            _auntUserinfo.accesstoken,
            widget._complete,
            IdentityStatus.aunt.index.toString(),
            page: _page.toString())
        .then((value) {
      if (value is OrderEntity) {
        _refreshController.loadComplete();

        if (value.havemore == 0) {
          _refreshController.loadNoData();
          _haveMore = false;
        }
        _orderList.addAll(value.orderList);
        setState(() {});
      } else {
        _refreshController.loadFailed();
      }
    });
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    _auntUserinfo = Provider.of<AuntEntity>(context).userinfo;
    return Container(
      color: Colors.redAccent,
      child: SmartRefresher(
          enablePullDown: true,
          enablePullUp: true,
          header: WaterDropHeader(),
          footer: CustomFooter(
            builder: (BuildContext context, LoadStatus mode) {
              Widget body;
              if (mode == LoadStatus.idle) {
                body = Text("pull up load");
              } else if (mode == LoadStatus.loading) {
                body = CupertinoActivityIndicator();
              } else if (mode == LoadStatus.failed) {
                body = Text("Load Failed!Click retry!");
              } else if (mode == LoadStatus.canLoading) {
                body = Text("release to load more");
              } else {
                body = Text("No more Data");
              }
              return Container(
                height: 55.0,
                child: Center(child: body),
              );
            },
          ),
          controller: _refreshController,
          onRefresh: _onRefresh,
          onLoading: _onLoading,
          child: ListView.builder(
            scrollDirection: Axis.vertical,
            itemCount: _orderList.length,
            itemBuilder: (BuildContext context, int index) {
              return OrderListItem(_orderList[index], index);
            },
          )),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

class OrderListItem extends StatelessWidget {
  final OrderEntityOrderList _orderListItem;
  final int dex;

  OrderListItem(this._orderListItem, this.dex);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(top: 10, left: 5, right: 5),
      child: GestureDetector(
        onTap: (){
          String orderId = _orderListItem.orderid.toString();
          String auntId = _orderListItem.auntid.toString();
          AuntApp.router.navigateTo(context, Routes.orderDetail+"?orderId=$orderId&orderType=2&aunt=$auntId");
        },
        child: Stack(
          children: [
            Center(
              child: Container(
                child: Column(
                  children: <Widget>[
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: _addWidget(),
                    ),
                  ],
                ),
                decoration: BoxDecoration(color: AuntColors.AWHITE,borderRadius: BorderRadius.circular(10)),
              ),
            ),
          ],
        ),
      ),
    );
  }

  List<Widget> _addWidget() {
    List<Widget> widgets = [];
    widgets.add(Padding(
      padding: const EdgeInsets.only(right: 10, left: 10, top: 14, bottom: 5),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(_orderListItem.servername),
          Text(_orderListItem.state),
        ],
      ),
    ));
    if(!ObjectUtil.isEmptyString( _orderListItem.timetitle)){
      widgets.add(_buildLine("上门时间", _orderListItem.timetitle));
    }

    if (_orderListItem.exceptTime > 0) {
      widgets.add(_buildLine("预计时长", _orderListItem.exceptTime.toString()));
    }
    if(!ObjectUtil.isEmptyString( _orderListItem.address)){
      widgets.add(_buildMultipleLine("服务地址", _orderListItem.address));
    }

    widgets.add(Divider(
      height: 2.0,
      indent: 10,
      endIndent: 10,
      color: AuntColors.AORANGE,
    ),);
    widgets.add(SizedBox(height:40,child: Center(child: Text('点击查看'))));
    return widgets;
  }

  Widget _buildLine(String title, String content) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Icon(
            Icons.circle,
            color: AuntColors.AORANGE,
            size: ScreenUtil().getWidth(10),
          ),
          SizedBox(
            width: ScreenUtil().getWidth(5),
          ),
          Text("$title: $content"),
        ],
      ),
    );
  }

  Widget _buildMultipleLine(String title, String content) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Center(
                child: Icon(
                  Icons.circle,
                  color: AuntColors.AORANGE,
                  size: ScreenUtil().getWidth(10),
                ),
              ),
              SizedBox(
                width: ScreenUtil().getWidth(5),
              ),
              Text(title + ": "),
            ],
          ),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  content,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
